<?php
if (!defined("KU6_PROJECT")) {
	die("hacking attack");
}
function verifyGet(&$msg) {
    //@todo 增加多个api支持，系统需要重构，目前不能灵活支持多个api
    if (!isset($_GET['api']) || !$_GET['api'] || $_GET['api'] != 'Recommend.GetARList') {
        $msg = 'uri params invalid';
        return FALSE;
    }
    if (!isset($_GET['cookie_id']) || !$_GET['cookie_id']) {
        $msg = "cookid is empty";
    	return FALSE;
    }
    if (!isset($_GET['sig']) || !$_GET['sig']) {
    }
    if (isset($_GET['recommend_num']) &&  (!is_numeric($_GET['recommend_num']) || $_GET['recommend_num'] < 0 || $_GET['recommend_num'] > MAX_SUGGEST_NUM) ) {
    	$msg = "recommend video number error";
    	return FALSE;
    }

    $_GET['viewed_list_sorted'] = array();
    $_GET['viewed_list_unsorted'] = array();
    if (isset($_GET['viewed_list']) && $_GET['viewed_list']) {
        $ids = explode(",", $_GET['viewed_list']);
        $ids = array_splice($ids, -2, 2);

        $_GET['viewed_list_unsorted'] = $ids;
        if (sortVids($ids)) {
            $_GET['viewed_list_sorted'] = $ids;
        }
    } else {
        $_GET['viewed_list'] = "";
    }

    if (sizeof($_GET['viewed_list_sorted']) > 4) {
        $msg = 'invalid visited video ids';
        return FALSE;
    }
    
    return TRUE;
}

function verifyCookid($cookid, $sig) {
    return md5($cookid.MD5_TOKEN)==$sig;
}

/**
 * @param Array $vids 最近播放视频id
 * @return String 最新观看的视频ID
 */
function getViewingVideoId($vids) {
    $vids = is_array($vids) ? $vids : array($vids);
    $id = array_pop($vids);
    $id = $id ? $id : 0;

    return $id;
}

/**
 * 按照字母序重排观看的视频id
 *
 * @param Array $vids 视频id数组
 * @return Boolean
 */
function sortVids(&$vids) {
    return rsort($vids, SORT_STRING);
}

/**
 * 按照二维数组第二维的rank进行降序排列
 */
function sortByConf($arra, $arrb) {
    if ($arra['CONF'] == $arrb['CONF']) {
        return 0;
    }
    return ($arra['CONF'] < $arrb['CONF']) ? 1 : -1;
}

/**
 * 按Conf升序
 */
function sortByConfAsc($arra, $arrb) {
    if ($arra['CONF'] == $arrb['CONF']) {
        return 0;
    }
    return ($arra['CONF'] < $arrb['CONF']) ? -1 : 1;
}

/**
 * 返回json字符串
 */
function populateResult($return, $cb=null) {
//    header('Content-Type:text/javascript;charset=utf8');
    if ($cb) {
    	die( "{$cb}(".json_encode($return).");" ); 
    }
    die( json_encode($return) );   
}

/**
 * black hole cache
 */
class NullCache
{
    public function __construct() {
    }

    public function get() {
        return FALSE;
    }

    public function set() {
        return TRUE;
    }
}

class RedisCache
{
    private $handle = NULL;
    private $db = NULL;
    private $connected = FALSE;

    public function __construct($config, $db = NULL)
    {
        $this->db = $db;
        try {
            $this->handle = new Redis();
            $this->handle->connect($config[0], $config[1]);
            $this->connected = TRUE;
        } catch (Exception $e) {
            $this->connected = FALSE;
        }

        if ( ($db != 0) && ! is_null($db) ) {
            if ($this->connected) {
                $this->handle->select($db);
            }
        }
    }

    public function get($key) {
        if (!$this->connected) {
            return FALSE;
        }

        if (is_array($key)) {
            $ret = $this->handle->sUnion($key);
        } else {
            $ret = $this->handle->sMembers($key);
        }
        //$ret = $this->handle->lGetRange($key, 0, -1);
        foreach ($ret as &$row) {
            $row = unserialize($row);
        }

        return $ret;
    }

    //key value set
    public function kvset($key, $value) {
        if (!$this->connected) {
            return FALSE;
        }
        $value = serialize($value);

        return $this->handle->set($key, $value);
    }

    //multiple get
    public function mget($arr) {
        if (!is_array($arr)) {
            $arr = array($arr);
        }
        if (!$this->connected) {
            return FALSE;
        }

        return $this->handle->mget($arr);
    }

    public function set($key, $value) {
        if (!$this->connected) {
            return FALSE;
        }

        $value = serialize($value);
        //return $this->handle->rPush($key, $value);
        return $this->handle->sAdd($key, $value);
    }

    public function flush() {
        if (!$this->connected) {
            return FALSE;
        }
        $flag = $this->handle->flushDB();

        return $flag;
    }

    public function __destruct() {
        if ($this->connected) {
            $this->handle->close();
        }
    }
}

/**
 * 返回redis缓存
 */
function getCacher($db = NULL)
{
    global $g_redis;
    static $redis = array();

    if ( !is_null($db)) {
        $db = (int) $db;
    } else {
        $db = 0;
    }

    if (isset($redis[$db]))
        return $redis[$db];

    $redis[$db] = new RedisCache($g_redis, $db);

    return $redis[$db];
}

/**
 * 按照当前日期, 时间，决定读写redis的哪个DB 0/1
 */
function getRedisRWDB()
{
    global $g_inmigrate, $g_specified, $g_migratedb;

    if (isset($g_specified) && $g_specified) {
        return $g_migratedb;
    }

    $db = 0;

    $day = date('d');
    $day = (int) $day;
    if ($day % 2) {
        $db = 0;
    } else {
        $db = 1;
    }

    if (isset($g_inmigrate) && $g_inmigrate) {
        $db = $db ? 0 : 1;
    }

    return $db;
}

/**
 * 获得cache key
 */
function getCacheKey($vid)
{
    $vid = str_replace(' ', '_', $vid);
    $vid = str_replace('&', '_', $vid);
    return $vid;
}

/**
 * 获得logger
 */
function getLogger() {
    static $logger = NULL;
    if ($logger) {
        return $logger;
    }
    require dirname(__FILE__) . '/Log.php';
    $logfile = "/tmp/recommend/recommend_" . date('Ymd') . ".log";
    $ident   = '';
    $conf = array(
            'lineFormat' => '[%1$s] [%3$s] %5$s(%6$s): %4$s',
            'timeFormat' => '%Y-%m-%d %H:%M:%S',
            'mode' => '0666'
        );
    $level   = PEAR_LOG_INFO;

    $logger  = Log::singleton('file', $logfile, $ident, $conf, $level);
    return $logger;
}

function getTestConfig($table) {
    $arr = array(
        'default'=>array(
            'InviteVideoTable'=>array(
            	'table'=>'ku6_log_model_ass_rule',
                'lhand'=>'lhand',
                'rhand'=>'rhand',
                'conf'=>'conf'
            ),                
    		'HotVideoTable'=>array(
            	'table'=>'ku6_log_hot_video_rank',
                'video_id'=>'video_id',
                'video_rank'=>'visit_user_num'
            ),
            'RecomendExposureTable'=>array(
                'table'=>'ku6_log_user_video_rec',
                'userid'=>'userid',
                'visit_video_id1'=>'visit_video_id1',
                'visit_video_id2'=>'visit_video_id2',
                'visit_video_id3'=>'visit_video_id3',
                'visit_video_id4'=>'visit_video_id4',
                'rec_video_id1'=>'rec_video_id1',
                'rec_video_id2'=>'rec_video_id2',
                'rec_video_id3'=>'rec_video_id3',
                'rec_video_id4'=>'rec_video_id4',
                'rec_video_id5'=>'rec_video_id5',
                'rec_video_id6'=>'rec_video_id6',
                'rec_video_id7'=>'rec_video_id7',
                'rec_video_id8'=>'rec_video_id8',
                'rec_time'=>'rec_time',
                'data_desc'=>'data_desc'
            )            
        ),
        'test1'=>array(
            'InviteVideoTable'=>array(
            	'table'=>'ku6_log_ass_rule',
                'lhand'=>'lhand',
                'rhand'=>'rhand',
                'conf'=>'conf'
            ),                
    		'HotVideoTable'=>array(
            	'table'=>'ku6_video_rank',
                'video_id'=>'video_id',
                'video_rank'=>'video_rank'
            ),
            'RecomendExposureTable'=>array(
                'table'=>'ku6_log_user_video_rec',
                'userid'=>'userid',
                'visit_video_id1'=>'visit_video_id1',
                'visit_video_id2'=>'visit_video_id2',
                'visit_video_id3'=>'visit_video_id3',
                'visit_video_id4'=>'visit_video_id4',
                'rec_video_id1'=>'rec_video_id1',
                'rec_video_id2'=>'rec_video_id2',
                'rec_video_id3'=>'rec_video_id3',
                'rec_video_id4'=>'rec_video_id4',
                'rec_video_id5'=>'rec_video_id5',
                'rec_video_id6'=>'rec_video_id6',
                'rec_video_id7'=>'rec_video_id7',
                'rec_video_id8'=>'rec_video_id8',
                'rec_time'=>'rec_time',
                'data_desc'=>'data_desc'
            )            
        ),
        'test2'=>array(
            'InviteVideoTable'=>array(
            	'table'=>'ku6_log_ass_rule_new',
                'lhand'=>'lhand',
                'rhand'=>'rhand',
                'conf'=>'conf'
            ),                
    		'HotVideoTable'=>array(
            	'table'=>'ku6_video_rank',
                'video_id'=>'video_id',
                'video_rank'=>'video_rank'
            ),
            'RecomendExposureTable'=>array(
                'table'=>'ku6_log_user_video_rec',
                'userid'=>'userid',
                'visit_video_id1'=>'visit_video_id1',
                'visit_video_id2'=>'visit_video_id2',
                'visit_video_id3'=>'visit_video_id3',
                'visit_video_id4'=>'visit_video_id4',
                'rec_video_id1'=>'rec_video_id1',
                'rec_video_id2'=>'rec_video_id2',
                'rec_video_id3'=>'rec_video_id3',
                'rec_video_id4'=>'rec_video_id4',
                'rec_video_id5'=>'rec_video_id5',
                'rec_video_id6'=>'rec_video_id6',
                'rec_video_id7'=>'rec_video_id7',
                'rec_video_id8'=>'rec_video_id8',
                'rec_time'=>'rec_time',
                'data_desc'=>'data_desc'
            )     
        ),
        
    ); 
    $test = !isset($_GET['test2']) ? DEFAULT_TABLE_STRUCT:'test2';
    if (!isset($arr[$test][$table])) {
    	return false;
    }
    return $arr[$test][$table];
}

function alert($msg = '', $alertType) {
    $logger = getLogger();
    $logger->log($msg);
    if (!IS_ALERT) {
    	return ;
    }
    require_once dirname(__FILE__) . '/http.php';

    $serverIp = $_SERVER["SERVER_ADDR"];

    #发送报警信息
    $postParams = array();
    $options = array(
        'max_redir'    => 1,
        'conn_retry'   => 1,
        'conn_timeout' => 10,
        'timeout'      => 10,
        'user_post'    => FALSE,
    );
    $params = array(
        'source'  => 301,
        'host'    => $serverIp,
        'type'    => $alertType,
        'level'   => 'fatal',
        'datanum' => 1,
        'msg'     => $msg,
        'happen_time' => date('Y-m-d H:i:s'),
    );
    #$url = 'http:// 10.150.9.13';
    $url = 'http://api.monitor.sdo.com/error_report.php?'
         . http_build_query($params);
    
    try {
        $response = http_post($url, $postParams, $options);
        $logger->log($url.':'.$response);
    } catch (Exception $ex) {
        $logger->log($url.':'.$ex->getMessage());
        return FALSE;
    }
    return TRUE;
}
